package houduan;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet(name = "UeditorServlet", urlPatterns = {"/UeditorServlet"})

public class UeditorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // 获取用户信息
    private String getUserFromId(Integer userId) {
        if (userId != null) {
            // 这里假设你有一个方法从会话中获取用户信息
            User user = LoginServlet.userSessionMap.get(userId);
            if (user != null) {
                return user.getUsername();
            }
        }
        return null;
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 可以使用这个方法来处理 GET 请求（通常是调试用）
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的编码统一为UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        PrintWriter out = response.getWriter();

        // 获取当前登录用户的ID，假设已经按前面提到的方式将会话标识 userSessionId 存储在会话中
        Integer userSessionId = (Integer) request.getSession().getAttribute("userSessionId");
        if (userSessionId == null) {
            out.println("<html><body><h1>请先登录！</h1></body></html>");
            return;
        }

        // 根据用户 ID 获取用户名
        String author = getUserFromId(userSessionId);
        if (author == null) {
            out.println("<html><body><h1>获取用户信息失败，请联系管理员！</h1></body></html>");
            return;
        }

        // 获取帖子标题
        String title = request.getParameter("title");

        // 获取富文本编辑器中的内容
        String content = request.getParameter("editorValue");  // 此为隐藏字段内容（编辑器内容）
        
        String category = request.getParameter("category");

        // 检查内容是否为空
        if (title == null || title.trim().isEmpty()) {
            out.println("<html><body><h1>标题不能为空！</h1></body></html>");
            return;
        }
        if (content == null || content.trim().isEmpty()) {
            out.println("<html><body><h1>内容不能为空！</h1></body></html>");
            return;
        }

        // 数据库连接配置（这里使用的是示例数据，请根据自己的数据库配置修改）
        String dbUrl = "jdbc:mysql://localhost:3306/lczmysql";
        String dbUsername = "root";
        String dbPassword = "123456";

        try {
            // 加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
            Connection connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
            
            // 准备插入帖子数据的SQL语句
            String sql = "INSERT INTO topic (username, title, context,category) VALUES (?,?,?,?)";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, author);   // 设置作者
            preparedStatement.setString(2, title);    // 设置标题
            preparedStatement.setString(3, content);  // 设置编辑器内容（帖子内容）
            preparedStatement.setString(4, category); 

            // 执行插入操作
            int rowsInserted = preparedStatement.executeUpdate();
            if (rowsInserted > 0) {
                // 插入成功，返回成功页面或其他逻辑
                out.println("<html><body><h1>帖子发布成功！<a href='shouye.jsp'>返回首页</a></h1></body></html>");
            } else {
                out.println("<html><body><h1>帖子发布失败，请重试！</h1></body></html>");
            }

            // 关闭数据库连接和PreparedStatement
            preparedStatement.close();
            connection.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            out.println("<html><body><h1>发生错误：" + e.getMessage() + "</h1></body></html>");
        }
    }

    // 处理通用请求的部分
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.println("<html><body>");
            out.println("<h1>Servlet UeditorServlet at " + request.getContextPath() + "</h1>");
            out.println("</body></html>");
        }
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
